import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Typography,
  Space,
  Button,
  Progress,
  Tag,
  List,
  Badge,
  Select,
  Spin
} from 'antd';
import {
  ShopOutlined,
  UserOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  DatabaseOutlined,
  ReloadOutlined,
  CheckCircleOutlined,
  InfoCircleOutlined,
  WarningOutlined,
  CloseCircleOutlined,
  CloudServerOutlined,
  SecurityScanOutlined,
  ApiOutlined,
  MonitorOutlined,
  SettingOutlined,
  RocketOutlined
} from '@ant-design/icons';
import { usePlatformStore } from '../../stores/platform';

const { Text } = Typography;

interface ChartData {
  name: string;
  value: number;
  trend: 'up' | 'down' | 'stable';
  percentage: number;
}

interface SystemMetric {
  name: string;
  value: number;
  unit: string;
  status: 'normal' | 'warning' | 'critical';
  threshold: number;
}

interface ActivityItem {
  id: string;
  type: 'success' | 'warning' | 'error' | 'info';
  title: string;
  description: string;
  time: string;
  user?: string;
}

interface SystemStatusItem {
  name: string;
  status: 'healthy' | 'warning' | 'error';
  uptime: string;
  responseTime: string;
  requests: string;
}

const PlatformDashboard: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [timeRange, setTimeRange] = useState<string>('7d');
  const { user } = usePlatformStore();

  const handleRefresh = () => { 
  };

  // 硬编码的统计数据
  const stats = {
    totalTenants: 156,
    activeUsers: 2847,
    usedStorage: 1247.5,
    totalUsers: 3245
  };

  if (loading) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '400px' 
      }}>
        <Spin size="large" />
      </div>
    );
  }

  // 定时刷新数据
  useEffect(() => {
    const interval = setInterval(() => {
      // 模拟数据刷新
      console.log('数据刷新');
    }, 30000); // 30秒刷新一次

    return () => clearInterval(interval);
  }, []);

  // 核心指标数据
  const coreMetrics: ChartData[] = [
    {
      name: '总租户数',
      value: stats?.totalTenants || 156,
      trend: 'up',
      percentage: 12.5
    },
    {
      name: '活跃用户',
      value: stats?.activeUsers || 2847,
      trend: 'up',
      percentage: 8.3
    },
    {
      name: '存储使用',
      value: stats?.usedStorage || 1247.5,
      trend: 'up',
      percentage: 15.2
    },
    {
      name: 'API调用',
      value: 98765,
      trend: 'down',
      percentage: -3.1
    }
  ];

  // 系统性能指标
  const systemMetrics: SystemMetric[] = [
    { name: 'CPU使用率', value: 45.2, unit: '%', status: 'normal', threshold: 80 },
    { name: '内存使用', value: 67.8, unit: '%', status: 'normal', threshold: 85 },
    { name: '磁盘使用', value: 82.1, unit: '%', status: 'warning', threshold: 80 },
    { name: '网络延迟', value: 23.5, unit: 'ms', status: 'normal', threshold: 100 }
  ];

  // 最近活动
  const recentActivities: ActivityItem[] = [
    {
      id: '1',
      type: 'success',
      title: '新租户注册',
      description: '阿里云科技成功注册企业版账户',
      time: '2024-12-10 15:30:00',
      user: '系统'
    },
    {
      id: '2',
      type: 'info',
      title: '系统升级',
      description: '平台核心服务已升级到v2.1.0版本',
      time: '2024-12-10 14:45:00',
      user: '管理员'
    },
    {
      id: '3',
      type: 'warning',
      title: '存储告警',
      description: '数据库存储使用率超过80%阈值',
      time: '2024-12-10 13:20:00',
      user: '监控系统'
    },
    {
      id: '4',
      type: 'success',
      title: '性能优化',
      description: 'API响应时间优化完成，平均提升25%',
      time: '2024-12-10 12:15:00',
      user: '技术团队'
    }
  ];

  // 快速操作
  const quickActions = [
    {
      title: '租户管理',
      description: '管理所有租户信息',
      icon: <ShopOutlined style={{ fontSize: 28, color: '#1890ff' }} />,
      path: '/platform/tenants',
      count: stats?.totalTenants || 0,
      color: '#1890ff'
    },
    {
      title: '用户管理',
      description: '用户权限与角色管理',
      icon: <UserOutlined style={{ fontSize: 28, color: '#52c41a' }} />,
      path: '/platform/users',
      count: stats?.totalUsers || 0,
      color: '#52c41a'
    },
    {
      title: '系统监控',
      description: '实时系统性能监控',
      icon: <MonitorOutlined style={{ fontSize: 28, color: '#722ed1' }} />,
      path: '/platform/monitor',
      count: 0,
      color: '#722ed1'
    },
    {
      title: '安全中心',
      description: '安全策略与风险管理',
      icon: <SecurityScanOutlined style={{ fontSize: 28, color: '#fa541c' }} />,
      path: '/platform/security',
      count: 3,
      color: '#fa541c'
    },
    {
      title: 'API管理',
      description: 'API接口管理与文档',
      icon: <ApiOutlined style={{ fontSize: 28, color: '#13c2c2' }} />,
      path: '/platform/api',
      count: 0,
      color: '#13c2c2'
    },
    {
      title: '系统设置',
      description: '平台配置与参数设置',
      icon: <SettingOutlined style={{ fontSize: 28, color: '#faad14' }} />,
      path: '/platform/settings',
      count: 0,
      color: '#faad14'
    }
  ];

  // 系统状态
  const systemStatusData: SystemStatusItem[] = [
    {
      name: 'API网关',
      status: 'healthy',
      uptime: '99.9%',
      responseTime: '120ms',
      requests: '1.2M/day'
    },
    {
      name: '认证服务',
      status: 'healthy',
      uptime: '99.8%',
      responseTime: '85ms',
      requests: '856K/day'
    },
    {
      name: '数据库集群',
      status: 'warning',
      uptime: '99.5%',
      responseTime: '45ms',
      requests: '2.3M/day'
    },
    {
      name: 'Redis缓存',
      status: 'healthy',
      uptime: '99.9%',
      responseTime: '12ms',
      requests: '5.6M/day'
    },
    {
      name: '消息队列',
      status: 'healthy',
      uptime: '99.7%',
      responseTime: '28ms',
      requests: '890K/day'
    }
  ];

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'healthy': return '#52c41a';
      case 'warning': return '#faad14';
      case 'error': return '#ff4d4f';
      default: return '#d9d9d9';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'healthy': return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
      case 'warning': return <WarningOutlined style={{ color: '#faad14' }} />;
      case 'error': return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />;
      default: return <InfoCircleOutlined style={{ color: '#d9d9d9' }} />;
    }
  };

  const getTrendIcon = (trend: string, percentage: number) => {
    if (trend === 'up') {
      return <ArrowUpOutlined style={{ color: '#52c41a', fontSize: 12 }} />;
    } else if (trend === 'down') {
      return <ArrowDownOutlined style={{ color: '#ff4d4f', fontSize: 12 }} />;
    }
    return null;
  };

  const getActivityIcon = (type: string) => {
    switch (type) {
      case 'success': return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
      case 'warning': return <WarningOutlined style={{ color: '#faad14' }} />;
      case 'error': return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />;
      case 'info': return <InfoCircleOutlined style={{ color: '#1890ff' }} />;
      default: return <InfoCircleOutlined style={{ color: '#d9d9d9' }} />;
    }
  };

  const getMetricStatus = (metric: SystemMetric) => {
    if (metric.value >= metric.threshold) {
      return { color: '#ff4d4f', status: 'exception' };
    } else if (metric.value >= metric.threshold * 0.8) {
      return { color: '#faad14', status: 'active' };
    }
    return { color: '#52c41a', status: 'success' };
  };

  return (
    <div >
      {/* 页面头部 */}
      <div style={{ 
        marginBottom: 24, 
        padding: '24px',
        background: '#ffffff',
        borderRadius: 8,
        boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.03), 0 1px 6px -1px rgba(0, 0, 0, 0.02), 0 2px 4px 0 rgba(0, 0, 0, 0.02)',
        border: '1px solid #f0f0f0'
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: 24, fontWeight: 600, color: '#262626', marginBottom: 8 }}>
              平台管理中心
            </div>
            <div style={{ fontSize: 14, color: '#8c8c8c' }}>
              实时监控系统状态，管理平台资源
            </div>
          </div>
          <Space size="middle">
            <Select
              value={timeRange}
              onChange={setTimeRange}
              style={{ width: 120 }}
              options={[
                { label: '今天', value: '1d' },
                { label: '7天', value: '7d' },
                { label: '30天', value: '30d' },
                { label: '90天', value: '90d' }
              ]}
            />
            <Button 
              type="primary" 
              icon={<ReloadOutlined />} 
              onClick={handleRefresh}
              loading={loading}
            >
              刷新数据
            </Button>
          </Space>
        </div>
      </div>

      {/* 核心指标卡片 */}
      <Row gutter={[24, 24]} style={{ marginBottom: 24 }}>
        {coreMetrics.map((metric, index) => {
          const colors = ['#1890ff', '#52c41a', '#faad14', '#722ed1'];
          const icons = [<ShopOutlined />, <UserOutlined />, <DatabaseOutlined />, <ApiOutlined />];
          return (
            <Col xs={24} sm={12} lg={6} key={index}>
              <Card 
                style={{ 
                  borderRadius: 8,
                  boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.03), 0 1px 6px -1px rgba(0, 0, 0, 0.02), 0 2px 4px 0 rgba(0, 0, 0, 0.02)',
                  border: '1px solid #f0f0f0'
                }}
                bodyStyle={{ padding: '24px' }}
              >
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
                      <div style={{ 
                        padding: 8, 
                        borderRadius: 8, 
                        background: colors[index], 
                        color: 'white',
                        marginRight: 12
                      }}>
                        {React.cloneElement(icons[index], { style: { fontSize: 20 } })}
                      </div>
                      <Text type="secondary" style={{ fontSize: 14 }}>{metric.name}</Text>
                    </div>
                    <div style={{ marginBottom: 8 }}>
                      <Text style={{ fontSize: 24, fontWeight: 600, color: '#262626' }}>
                        {metric.name === '存储使用' ? `${metric.value}GB` : metric.value.toLocaleString()}
                      </Text>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      {getTrendIcon(metric.trend, metric.percentage)}
                      <Text 
                        style={{ 
                          marginLeft: 4, 
                          fontSize: 12,
                          color: metric.trend === 'up' ? '#52c41a' : '#ff4d4f'
                        }}
                      >
                        {metric.percentage > 0 ? '+' : ''}{metric.percentage}%
                      </Text>
                      <Text type="secondary" style={{ marginLeft: 8, fontSize: 12 }}>vs 上周</Text>
                    </div>
                  </div>
                </div>
              </Card>
            </Col>
          );
        })}
      </Row>

      {/* 主要内容区域 */}
      <Row gutter={[24, 24]}>
        {/* 左侧列 */}
        <Col xs={24} lg={16}>
          {/* 快速操作 */}
          <Card 
            title={
              <Space>
                <RocketOutlined style={{ color: '#1890ff' }} />
                快速操作
              </Space>
            }
            style={{ 
              marginBottom: 16, 
              borderRadius: 8,
              boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.03), 0 1px 6px -1px rgba(0, 0, 0, 0.02), 0 2px 4px 0 rgba(0, 0, 0, 0.02)',
              border: '1px solid #f0f0f0'
            }}
            bodyStyle={{ padding: '24px' }}
          >
            <Row gutter={[24, 24]}>
              {quickActions.map((action, index) => (
                <Col xs={12} sm={8} lg={8} key={index}>
                  <Card 
                    size="small" 
                    hoverable
                    style={{ 
                      textAlign: 'center', 
                      cursor: 'pointer',
                      borderRadius: 8,
                      border: '1px solid #f0f0f0',
                      transition: 'all 0.2s ease'
                    }}
                    bodyStyle={{ padding: '16px 12px' }}
                    onClick={() => window.location.href = action.path}
                  >
                    <div style={{ marginBottom: 8 }}>
                      {action.icon}
                    </div>
                    <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 4, color: '#262626' }}>
                      {action.title}
                    </div>
                    <div style={{ fontSize: 12, color: '#8c8c8c', marginBottom: 8 }}>
                      {action.description}
                    </div>
                    {action.count > 0 && (
                      <Badge 
                        count={action.count} 
                        style={{ backgroundColor: action.color }} 
                        size="small"
                      />
                    )}
                  </Card>
                </Col>
              ))}
            </Row>
          </Card>

          {/* 系统性能监控 */}
          <Card 
            title={
              <Space>
                <MonitorOutlined style={{ color: '#722ed1' }} />
                系统性能监控
              </Space>
            }
            style={{ 
              borderRadius: 8,
              boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.03), 0 1px 6px -1px rgba(0, 0, 0, 0.02), 0 2px 4px 0 rgba(0, 0, 0, 0.02)',
              border: '1px solid #f0f0f0'
            }}
            bodyStyle={{ padding: '24px' }}
          >
            <Row gutter={[16, 16]}>
              {systemMetrics.map((metric, index) => {
                const status = getMetricStatus(metric);
                return (
                  <Col xs={12} sm={6} key={index}>
                    <div style={{ textAlign: 'center', padding: '16px 8px' }}>
                      <div style={{ marginBottom: 8 }}>
                        <Text type="secondary" style={{ fontSize: 12 }}>{metric.name}</Text>
                      </div>
                      <div style={{ marginBottom: 8 }}>
                        <Text style={{ fontSize: 20, fontWeight: 'bold', color: status.color }}>
                          {metric.value}{metric.unit}
                        </Text>
                      </div>
                      <Progress 
                        percent={metric.value} 
                        size="small" 
                        strokeColor={status.color}
                        showInfo={false}
                        style={{ marginBottom: 4 }}
                      />
                      <Text type="secondary" style={{ fontSize: 10 }}>阈值: {metric.threshold}{metric.unit}</Text>
                    </div>
                  </Col>
                );
              })}
            </Row>
          </Card>
        </Col>

        {/* 右侧列 */}
        <Col xs={24} lg={8}>
          {/* 系统状态 */}
          <Card 
            title={
              <Space>
                <CloudServerOutlined style={{ color: '#52c41a' }} />
                系统状态
              </Space>
            }
            style={{ 
              marginBottom: 16, 
              borderRadius: 8,
              boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.03), 0 1px 6px -1px rgba(0, 0, 0, 0.02), 0 2px 4px 0 rgba(0, 0, 0, 0.02)',
              border: '1px solid #f0f0f0'
            }}
            bodyStyle={{ padding: '24px' }}
          >
            <List
              size="small"
              dataSource={systemStatusData}
              renderItem={(item) => (
                <List.Item style={{ padding: '12px 0', borderBottom: '1px solid #f0f0f0' }}>
                  <List.Item.Meta
                    avatar={getStatusIcon(item.status)}
                    title={
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <span style={{ fontSize: 13, fontWeight: 'bold' }}>{item.name}</span>
                        <Tag color={getStatusColor(item.status)}>
                          {item.status === 'healthy' ? '正常' : 
                           item.status === 'warning' ? '警告' : '异常'}
                        </Tag>
                      </div>
                    }
                    description={
                      <div style={{ fontSize: 11, color: '#666' }}>
                        <div>运行时间: {item.uptime}</div>
                        <div>响应时间: {item.responseTime}</div>
                        <div>请求量: {item.requests}</div>
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default PlatformDashboard;